<?php

namespace api\modules\backend\controllers;

use Yii;
use yii\rest\ActiveController;
use common\library\traits\APITrait;
use common\commands\Common;
use yii\filters\auth\QueryParamAuth;

class ControllerBase extends ActiveController
{
    use APITrait;

    public function behaviors()
    {
        header('Access-Control-Allow-Origin:*');
        header("Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, DELETE, PATCH");
        header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
        Yii::$app->user->identityClass = 'api\modules\backend\models\User';

        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            $this->response(Common::getPackedResponse(SUCCESS, 'Success'));
        }

        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [],
        ];
        $behaviors['authenticator']['except'] = ['options'];
        return $behaviors;
    }

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        date_default_timezone_set('PRC');

        if (!parent::beforeAction($action)) {
            return false;
        }

        return true;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        unset($actions['create']);
        unset($actions['update']);
        unset($actions['delete']);
        unset($actions['view']);
        return $actions;
    }

    /**
     * @inheritdoc
     */
    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);
        if (empty($result)) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED')));
        } else {
            $this->success($result);
        }
    }
}